﻿using System;
using System.ComponentModel;
using System.DirectoryServices.AccountManagement;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Utilities;

namespace ADPasswordChanger.WebParts.WPAlterarSenha
{
    [ToolboxItemAttribute(false)]
    public partial class WPAlterarSenha : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public WPAlterarSenha()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        private bool GetDomainAndUserClaims(out string domain, out string user)
        {
            user = string.Empty;
            domain = string.Empty;
            try
            {
                SPClaimProviderManager clmProvider = SPClaimProviderManager.Local;

                if (clmProvider != null)
                {
                    user = clmProvider.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).Value;
                    int index = user.IndexOf('\\');
                    domain = user.Substring(0, index);
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string user;
            string domain;

            if (GetDomainAndUserClaims(out domain, out user))
            {
                lblUsuario.Text = user;
            }
            else
            {
                lblUsuario.Text = SPContext.Current.Web.CurrentUser.LoginName;
            }
            lblMensagemErro.Text = string.Empty;
        }

        public void AddSharePointNotification(string text, bool isErro)
        {
            lblMensagemErro.Text = text;
            if (isErro)
                lblMensagemErro.ForeColor = System.Drawing.Color.Red;
            else
                lblMensagemErro.ForeColor = System.Drawing.Color.Black;
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            CloseDialog();

        }

        private void CloseDialog()
        {
            HttpContext context = HttpContext.Current;
            if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
            {
                context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
                context.Response.Flush();
                context.Response.End();
            }
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            string usuario = string.Empty;
            string domain = string.Empty;

            usuario = lblUsuario.Text;
            domain = usuario.Substring(0, usuario.IndexOf('\\'));
            usuario = usuario.Substring(usuario.IndexOf('\\') + 1);


            try
            {
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, usuario, txtSenhaAntiga.Text))
                //using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ))
                {
                    UserPrincipal user = new UserPrincipal(ctx, usuario, txtSenhaAntiga.Text, true);
                    if (ctx.ValidateCredentials(usuario, txtSenhaAntiga.Text))
                    {
                        user = UserPrincipal.FindByIdentity(ctx, IdentityType.Name, usuario);
                        if (user != null)
                        {
                            //Change the password
                            user.ChangePassword(txtSenhaAntiga.Text, txtNovaSenha.Text);
                            user.Save();

                            AddSharePointNotification("Senha alterada com sucesso!", false);
                            SPUtility.Redirect(SPContext.Current.Web.Url + "/_layouts/closeConnection.aspx?loginasanotheruser=true", SPRedirectFlags.Default, this.Context);
                        }
                        else
                        {
                            AddSharePointNotification("Erro ao encontrar o usuário.", true);
                        }
                    }
                    else
                    {
                        AddSharePointNotification(string.Format("Usuário/Senha inválidos: Domain {0} - User {1}", domain, usuario), true);
                    }

                }
            }
            catch (Exception ex)
            {
                AddSharePointNotification("Erro ao alterar senha: " + ex.Message + "<br/>" + ex.StackTrace, true);
            }

        }

    }
}
